package com.charley.icloud.swagger.knife4j;

import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.apache.http.HttpHeaders;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.Ordered;

import java.util.HashMap;
import java.util.Map;

/**
 * 增强 {@link OpenAPI} 加入全局token 参数
 * 添加请求参数：把 token 作为请求头部参数传入后端
 */
public class DocketPostProcessor implements BeanPostProcessor, Ordered {

  @Override
  public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    if (bean instanceof OpenAPI) {
      // 接口安全配置
      ((OpenAPI) bean).components(new Components().securitySchemes(buildSecuritySchemes()))
      .addSecurityItem(new SecurityRequirement().addList(HttpHeaders.AUTHORIZATION));
    }
    return bean;
  }

  @Override
  public int getOrder() {
    return 0;
  }

  /**
   * 安全模式，这里配置通过请求头 Authorization 传递 token 参数
   */
  private Map<String, SecurityScheme> buildSecuritySchemes() {
    Map<String, SecurityScheme> securitySchemes = new HashMap<>();
    SecurityScheme securityScheme = new SecurityScheme()
            .type(SecurityScheme.Type.APIKEY) // 类型
            .name(HttpHeaders.AUTHORIZATION) // 请求头的 name
            .in(SecurityScheme.In.HEADER); // token 所在位置
    securitySchemes.put(HttpHeaders.AUTHORIZATION, securityScheme);
    return securitySchemes;
  }

}
